package com.yh.ldzl.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.InventoryService;
import com.yh.ldzl.domain.QcIqc;
import com.yh.ldzl.mapper.QcIqcMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yh.ldzl.mapper.QcRqcMapper;
import com.yh.ldzl.domain.QcRqc;
import com.yh.ldzl.service.IQcRqcService;
import com.yh.ldzl.service.QualityCheckNotificationService;

import javax.annotation.Resource;

/**
 * 退料检验单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-10
 */
@Service
public class QcRqcServiceImpl implements IQcRqcService 
{
    @Autowired
    private QcRqcMapper qcRqcMapper;
    @Autowired
    private QcIqcMapper qcIqcMapper;
    
    @Autowired
    private QualityCheckNotificationService qualityCheckNotificationService;

    @Resource
    private InventoryService inventoryService;
    @Resource
    private BasicService basicService;

    /**
     * 查询退料检验单
     * 
     * @param rqcId 退料检验单主键
     * @return 退料检验单
     */
    @Override
    public QcRqc selectQcRqcByRqcId(Long rqcId)
    {
        return qcRqcMapper.selectQcRqcByRqcId(rqcId);
    }

    /**
     * 查询退料检验单列表
     * 
     * @param qcRqc 退料检验单
     * @return 退料检验单
     */
    @Override
    public List<QcRqc> selectQcRqcList(QcRqc qcRqc)
    {
        return qcRqcMapper.selectQcRqcList(qcRqc);
    }
    /**
     * 自动编码
     */
    private String generateCode(Long type) {
        // 调用远程服务（消费模式，确保每次调用都会递增流水号）
        AjaxResult codeResult = basicService.automaticallyNumbersConsume(type);

        // 确保远程调用返回了结果对象
        if (codeResult == null) {
            throw new ServiceException(String.format("远程获取编码调用失败，返回结果为空，类型: %d", type));
        }

        // 根据该接口的特殊设计，编码直接存放在msg字段
        Object msg = codeResult.get(AjaxResult.MSG_TAG);
        Object code = codeResult.get(AjaxResult.CODE_TAG);
        System.out.println("编码是：" + code);
        // 确保编码内容不为空
        if (msg == null || msg.toString().isEmpty()) {
            throw new ServiceException(String.format("远程获取编码成功，但返回的编码为空，类型: %d, 返回信息: %s", type, msg));
        }

        // 从AjaxResult中正确取出msg部分作为编码
        return msg.toString();
    }

    /**
     * 新增退料检验单
     * 
     * @param qcRqc 退料检验单
     * @return 结果
     */
    @Override
    public int insertQcRqc(QcRqc qcRqc) {

        int success=0;
        try{
            qcRqc.setCreateBy(SecurityUtils.getUsername());
            TableDataInfo receipt = inventoryService.findReceipt_id_qc(qcRqc.getSourceDocId());
            List<?> list = receipt.getRows();
            List<Map<String, Object>> list1 = (List<Map<String, Object>>) list;
            System.out.println("list1 = " + list1);
            int totalRows = 0;
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> map = list1.get(i);

                // 只在第一次循环之后生成编码
                if (i != 0) {
                    String codeResult = generateCode(9L);
                    qcRqc.setRqcCode(codeResult);
                }
                qcRqc.setMaterialCode(map.get("goods_code").toString());
                qcRqc.setMaterialName(map.get("goods_name").toString());
                qcRqc.setMaterialSfn(map.get("stock_sfn").toString());
                qcRqc.setUnit(map.get("unit_name").toString());
                String receivedNumStr = map.get("recived_num").toString();
                BigDecimal receivedNum = new BigDecimal(receivedNumStr);
                qcRqc.setQuantityCheckNum(receivedNum);
                System.out.println(qcRqc);
                totalRows += qcRqcMapper.insertQcRqc(qcRqc);
            }
            success = totalRows == list.size() ? 1 : 0;


        }catch (Exception e){
            return 0;   // 1-全部成功，0-失败
        }
        return success;   // 1-全部成功，0-失败
    };


    /**
     * 修改退料检验单
     * 
     * @param qcRqc 退料检验单
     * @return 结果
     */
    @Override
    public int updateQcRqc(QcRqc qcRqc)
    {
        qcRqc.setUpdateBy(SecurityUtils.getUsername());

        // 1. 查询 line_id
        Long line_id = qcIqcMapper.selectCkItemRecptLineLineId(
                qcRqc.getSourceDocId(), qcRqc.getMaterialCode());
        System.out.println("line_id:" + line_id);

        // 2. 更新主表
        int row1 = qcRqcMapper.updateQcRqc(qcRqc);
        int row2=0;
        // 3. 更新明细状态
        if (qcRqc.getCheckResult().equals("1")){//检测单合格
            row2 = qcIqcMapper.updateCkItemRecptLineStatus(
                    line_id, "2", qcRqc.getRqcId());//将入库单明细状态改为合格
        }else if (qcRqc.getCheckResult().equals("2")){//检测单不合格
            row2 = qcIqcMapper.updateCkItemRecptLineStatus(
                    line_id, "3", qcRqc.getRqcId());//将入库单明细状态改为不合格
        }

        //判断出货单明细检测情况
        int testResults = qcIqcMapper.selectCkItemRecptTestResults(qcRqc.getSourceDocId());
        if (testResults==1) {//1.全部合格(所有行都已质检且状态为2/合格)
            inventoryService.updateCkProductRecptStatusStatus(qcRqc.getSourceDocId(),3L);
        }else if (testResults==2) {//2.全部不合格(所有行都已质检且状态为3/不合格)
            inventoryService.updateCkProductRecptStatusStatus(qcRqc.getSourceDocId(),4L);
        }else if (testResults==4) {//4.有合格也有不合格(存在合格和不合格的行，且没有未质检的行)
            inventoryService.updateCkProductRecptStatusStatus(qcRqc.getSourceDocId(),5L);
        }

        System.out.println("更新退料入库表:"+testResults+ "更新退料入库检测表:"+row1+ "更新退料入库详情表:"+row2);
        // 4. 必须都大于 0 才算成功
        return (row1 > 0 && row2 > 0) ? 1 : 0;

    }

    /**
     * 批量删除退料检验单
     * 
     * @param rqcIds 需要删除的退料检验单主键
     * @return 结果
     */
    @Override
    public int deleteQcRqcByRqcIds(Long[] rqcIds)
    {
        return qcRqcMapper.deleteQcRqcByRqcIds(rqcIds);
    }

    /**
     * 删除退料检验单信息
     * 
     * @param rqcId 退料检验单主键
     * @return 结果
     */
    @Override
    public int deleteQcRqcByRqcId(Long rqcId)
    {
        return qcRqcMapper.deleteQcRqcByRqcId(rqcId);
    }

    @Override
    public QcRqc selectQcRqcListSourceDocId(Long source_doc_id) {
        return qcRqcMapper.selectQcRqcListSourceDocId(source_doc_id);
    }

    @Override
    public List<Map<String, Object>> selectCkRtIssueQC(String rt_code, String rt_name) {
        return qcRqcMapper.selectCkRtIssueQC(rt_code,rt_name);
    }

    @Override
    public boolean updateCkRtIssueStatus(Long material_return_id) {
        return qcRqcMapper.updateCkRtIssueStatus(material_return_id)>0;
    }
}
